(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); EOL.namespace('csr911'); EOL.csr911.dialog = null; EOL.csr911.open = function(objId, objType, loginName, violationUrl, providerUserid) { if(objType == 'BidId') { $el('send', 'userAction', 'CLICK', 'BidViolation', { pageName: 'CandidateSelection', logEntries: { bidid: objId, client_userid: $('userId').value, freelancer_userid: providerUserid } }); } var request = new Request({ url: '/php/feedback/main/csr911HTML.php?type='+objType+'&username='+escape(loginName)+'&t=' + getDateTime(), method: 'get', onSuccess: function(req) { EOL.csr911.dialog = new EOL.dialog(req, {position: 'fixed', modal:true, close:true, className:'eol-reportviolation-dialog'}); EOL.csr911.dialog.show(); $('object_id').value = objId; if (violationUrl) { $('violation_url').value = violationUrl; } }, onFailure: function() {} }).send(); } EOL.csr911.submit = function() { var postData = $('csr911form').toQueryString(); if($('violationSubmitError')) { $('violationSubmitError').setStyle('display', 'none'); } var options = { url: '/php/feedback/main/csr_911.php?t=' + getDateTime(), method: 'post', data: postData, onSuccess: function(response) { var resp = eval( "(" + response + ")"); if( resp.status == 'success') { EOL.csr911.close(); var conf = new EOL.dialog(['Success','Your message was successfully sent!'], {position: 'fixed', modal:true, width: 300, close:true}).show(); if(/*bid report violation */ resp.data.BidId && !resp.data.mode) { EOL.proposals.hide('/job/'+ EOL.proposals.jobid +'/hideProposal', resp.data.BidId, 'hidden'); } return; } else { if(resp.data.BidId && !resp.data.mode) { $('violationSubmitError').setStyle('display', ''); } else { $$('[id$=_err]').each(function(elm){if (!elm.hasClass("displayNone")) {elm.addClass("displayNone")}; elm.innerHTML = "";}); var errArr = resp.errorMsgs; var errEl = resp.errorIds; var size = errArr.length; for(var i=0; i < size; i++) { $(errEl[i]+'_err').removeClass('displayNone').innerHTML = errArr[i]; } } return false; } }, onFailure: function() {alert('There was an error processing your request. Please try again.')} }; var req = new Request(options); req.send(); } EOL.csr911.submitSpam = function(bidid, providerUserId) { $el('send', 'useraction', 'CLICK', 'BidSpam', { pageName: 'CandidateSelection', logEntries: { bidid: bidid, client_userid: $('userId').value, freelancer_userid: providerUserId } }); var postData = 'mode=spam&id_type=BidId&object_id='+ bidid +'&violation_url=&subject='+ encodeURIComponent('Spam Report') + '&comments=' + encodeURIComponent('Spam Report'); var options = { url: '/php/feedback/main/csr_911.php?t=' + getDateTime(), method: 'post', data: postData, onSuccess: function(response) { var resp = eval( "(" + response + ")"); if(resp.status == 'success') { EOL.proposals.hide('/job/'+ EOL.proposals.jobid +'/hideProposal', resp.data.BidId, 'hidden'); return; } else { return false; } }, onFailure: function() {alert('There was an error processing your request. Please try again.')} }; var req = new Request(options); req.send(); } EOL.csr911.close = function() { EOL.csr911.dialog.hide(); } /* * Bid violation related functions */ EOL.csr911.bidViolationCommentFocus = function(el) { if(el.value == 'Enter details (optional)') { el.setStyle('color', '#000000'); el.value = ''; } } EOL.csr911.bidViolationCommentBlur = function(el) { if(!el.value) { el.setStyle('color', '#919191'); el.value = 'Enter details (optional)'; } } EOL.csr911.changeBidComments = function(el) { $('bidViolationArea').getElements('input[type=radio]').each(function(el) { if(el.checked) { $(el.value+'_comments').setStyle('display', ''); $('subject').value = $(el.value + '_text').innerHTML; } else { $(el.value+'_comments').setStyle('display', 'none'); } }); } /* * END - Bid violation related functions */ Fx.Elements=new Class({Extends:Fx.CSS,initialize:function(b,a){this.elements=this.subject=$$(b);this.parent(a)},compute:function(g,h,j){var c={};for(var d in g){var a=g[d],e=h[d],f=c[d]={};for(var b in a){f[b]=this.parent(a[b],e[b],j)}}return c},set:function(b){for(var c in b){if(!this.elements[c]){continue}var a=b[c];for(var d in a){this.render(this.elements[c],d,a[d],this.options.unit)}}return this},start:function(c){if(!this.check(c)){return this}var h={},j={};for(var d in c){if(!this.elements[d]){continue}var f=c[d],a=h[d]={},g=j[d]={};for(var b in f){var e=this.prepare(this.elements[d],b,f[b]);a[b]=e.from;g[b]=e.to}}return this.parent(h,j)}});Fx.Accordion=new Class({Extends:Fx.Elements,options:{fixedHeight:false,fixedWidth:false,display:0,show:false,height:true,width:false,opacity:true,alwaysHide:false,trigger:"click",initialDisplayFx:true,resetHeight:true},initialize:function(){var g=function(h){return h!=null};var f=Array.link(arguments,{container:Type.isElement,options:Type.isObject,togglers:g,elements:g});this.parent(f.elements,f.options);var b=this.options,e=this.togglers=$$(f.togglers);this.previous=-1;this.internalChain=new Chain();if(b.alwaysHide){this.options.link="chain"}if(b.show||this.options.show===0){b.display=false;this.previous=b.show}if(b.start){b.display=false;b.show=false}var d=this.effects={};if(b.opacity){d.opacity="fullOpacity"}if(b.width){d.width=b.fixedWidth?"fullWidth":"offsetWidth"}if(b.height){d.height=b.fixedHeight?"fullHeight":"scrollHeight"}for(var c=0,a=e.length;c=0?a-1:0)).chain(d)}else{d()}return this},detach:function(b){var a=function(c){c.removeEvent(this.options.trigger,c.retrieve("accordion:display"))}.bind(this);if(!b){this.togglers.each(a)}else{a(b)}return this},display:function(b,c){if(!this.check(b,c)){return this}var h={},g=this.elements,a=this.options,f=this.effects;if(c==null){c=true}if(typeOf(b)=="element"){b=g.indexOf(b)}if(b==this.previous&&!a.alwaysHide){return this}if(a.resetHeight){var e=g[this.previous];if(e&&!this.selfHidden){for(var d in f){e.setStyle(d,e[f[d]])}}}if((this.timer&&a.link=="chain")||(b===this.previous&&!a.alwaysHide)){return this}this.previous=b;this.selfHidden=false;g.each(function(l,k){h[k]={};var j;if(k!=b){j=true}else{if(a.alwaysHide&&((l.offsetHeight>0&&a.height)||l.offsetWidth>0&&a.width)){j=true;this.selfHidden=true}}this.fireEvent(j?"background":"active",[this.togglers[k],l]);for(var m in f){h[k][m]=j?0:l[f[m]]}if(!c&&!j&&a.resetHeight){h[k].height="auto"}},this);this.internalChain.clearChain();this.internalChain.chain(function(){if(a.resetHeight&&!this.selfHidden){var i=g[b];if(i){i.setStyle("height","auto")}}}.bind(this));return c?this.start(h):this.set(h).internalChain.callChain()}});var Accordion=new Class({Extends:Fx.Accordion,initialize:function(){this.parent.apply(this,arguments);var a=Array.link(arguments,{container:Type.isElement});this.container=a.container},addSection:function(c,b,e){c=document.id(c);b=document.id(b);var d=this.togglers.contains(c);var a=this.togglers.length;if(a&&(!d||e)){e=e!=null?e:a-1;c.inject(this.togglers[e],"before");b.inject(c,"after")}else{if(this.container&&!d){c.inject(this.container);b.inject(this.container)}}return this.parent.apply(this,arguments)}});(function(){Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(c,b){this.element=this.subject=document.id(c);this.parent(b);if(typeOf(this.element)!="element"){this.element=document.id(this.element.getDocument().body)}if(this.options.wheelStops){var d=this.element,e=this.cancel.pass(false,this);this.addEvent("start",function(){d.addEvent("mousewheel",e)},true);this.addEvent("complete",function(){d.removeEvent("mousewheel",e)},true)}},set:function(){var b=Array.flatten(arguments);if(Browser.firefox){b=[Math.round(b[0]),Math.round(b[1])]}this.element.scrollTo(b[0],b[1]);return this},compute:function(d,c,b){return[0,1].map(function(e){return Fx.compute(d[e],c[e],b)})},start:function(c,d){if(!this.check(c,d)){return this}var b=this.element.getScroll();return this.parent([b.x,b.y],[c,d])},calculateScroll:function(g,f){var d=this.element,b=d.getScrollSize(),h=d.getScroll(),j=d.getSize(),c=this.options.offset,i={x:g,y:f};for(var e in i){if(!i[e]&&i[e]!==0){i[e]=h[e]}if(typeOf(i[e])!="number"){i[e]=b[e]-j[e]}i[e]+=c[e]}return[i.x,i.y]},toTop:function(){return this.start.apply(this,this.calculateScroll(false,0))},toLeft:function(){return this.start.apply(this,this.calculateScroll(0,false))},toRight:function(){return this.start.apply(this,this.calculateScroll("right",false))},toBottom:function(){return this.start.apply(this,this.calculateScroll(false,"bottom"))},toElement:function(d,e){e=e?Array.from(e):["x","y"];var c=a(this.element)?{x:0,y:0}:this.element.getScroll();var b=Object.map(document.id(d).getPosition(this.element),function(g,f){return e.contains(f)?g+c[f]:false});return this.start.apply(this,this.calculateScroll(b.x,b.y))},toElementEdge:function(d,g,e){g=g?Array.from(g):["x","y"];d=document.id(d);var i={},f=d.getPosition(this.element),j=d.getSize(),h=this.element.getScroll(),b=this.element.getSize(),c={x:f.x+j.x,y:f.y+j.y};["x","y"].each(function(k){if(g.contains(k)){if(c[k]>h[k]+b[k]){i[k]=c[k]-b[k]}if(f[k]this.options.snap){this.cancel();this.document.addEvents({mousemove:this.bound.drag,mouseup:this.bound.stop});this.fireEvent("start",[this.element,a]).fireEvent("snap",this.element)}},drag:function(b){var a=this.options;if(a.preventDefault){b.preventDefault()}this.mouse.now=b.page;for(var c in a.modifiers){if(!a.modifiers[c]){continue}this.value.now[c]=this.mouse.now[c]-this.mouse.pos[c];if(a.invert){this.value.now[c]*=-1}if(a.limit&&this.limit[c]){if((this.limit[c][1]||this.limit[c][1]===0)&&(this.value.now[c]>this.limit[c][1])){this.value.now[c]=this.limit[c][1]}else{if((this.limit[c][0]||this.limit[c][0]===0)&&(this.value.now[c]d.left&&b.xd.top)},this).getLast();if(this.overed!=a){if(this.overed){this.fireEvent("leave",[this.element,this.overed])}if(a){this.fireEvent("enter",[this.element,a])}this.overed=a}},drag:function(a){this.parent(a);if(this.options.checkDroppables&&this.droppables.length){this.checkDroppables()}},stop:function(a){this.checkDroppables();this.fireEvent("drop",[this.element,this.overed,a]);this.overed=null;return this.parent(a)}});Element.implement({makeDraggable:function(a){var b=new Drag.Move(this,a);this.store("dragger",b);return b}});(function(){var a=function(d){var b=d.options.hideInputs;if(window.OverText){var c=[null];OverText.each(function(e){c.include("."+e.options.labelClass)});if(c){b+=c.join(", ")}}return(b)?d.element.getElements(b):null};Fx.Reveal=new Class({Extends:Fx.Morph,options:{link:"cancel",styles:["padding","border","margin"],transitionOpacity:!Browser.ie6,mode:"vertical",display:function(){return this.element.get("tag")!="tr"?"block":"table-row"},opacity:1,hideInputs:Browser.ie?"select, input, textarea, object, embed":null},dissolve:function(){if(!this.hiding&&!this.showing){if(this.element.getStyle("display")!="none"){this.hiding=true;this.showing=false;this.hidden=true;this.cssText=this.element.style.cssText;var d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode});if(this.options.transitionOpacity){d.opacity=this.options.opacity}var c={};Object.each(d,function(f,e){c[e]=[f,0]});this.element.setStyles({display:Function.from(this.options.display).call(this),overflow:"hidden"});var b=a(this);if(b){b.setStyle("visibility","hidden")}this.$chain.unshift(function(){if(this.hidden){this.hiding=false;this.element.style.cssText=this.cssText;this.element.setStyle("display","none");if(b){b.setStyle("visibility","visible")}}this.fireEvent("hide",this.element);this.callChain()}.bind(this));this.start(c)}else{this.callChain.delay(10,this);this.fireEvent("complete",this.element);this.fireEvent("hide",this.element)}}else{if(this.options.link=="chain"){this.chain(this.dissolve.bind(this))}else{if(this.options.link=="cancel"&&!this.hiding){this.cancel();this.dissolve()}}}return this},reveal:function(){if(!this.showing&&!this.hiding){if(this.element.getStyle("display")=="none"){this.hiding=false;this.showing=true;this.hidden=false;this.cssText=this.element.style.cssText;var d;this.element.measure(function(){d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode})}.bind(this));if(this.options.heightOverride!=null){d.height=this.options.heightOverride.toInt()}if(this.options.widthOverride!=null){d.width=this.options.widthOverride.toInt()}if(this.options.transitionOpacity){this.element.setStyle("opacity",0);d.opacity=this.options.opacity}var c={height:0,display:Function.from(this.options.display).call(this)};Object.each(d,function(f,e){c[e]=0});c.overflow="hidden";this.element.setStyles(c);var b=a(this);if(b){b.setStyle("visibility","hidden")}this.$chain.unshift(function(){this.element.style.cssText=this.cssText;this.element.setStyle("display",Function.from(this.options.display).call(this));if(!this.hidden){this.showing=false}if(b){b.setStyle("visibility","visible")}this.callChain();this.fireEvent("show",this.element)}.bind(this));this.start(d)}else{this.callChain();this.fireEvent("complete",this.element);this.fireEvent("show",this.element)}}else{if(this.options.link=="chain"){this.chain(this.reveal.bind(this))}else{if(this.options.link=="cancel"&&!this.showing){this.cancel();this.reveal()}}}return this},toggle:function(){if(this.element.getStyle("display")=="none"){this.reveal()}else{this.dissolve()}return this},cancel:function(){this.parent.apply(this,arguments);if(this.cssText!=null){this.element.style.cssText=this.cssText}this.hiding=false;this.showing=false;return this}});Element.Properties.reveal={set:function(b){this.get("reveal").cancel().setOptions(b);return this},get:function(){var b=this.retrieve("reveal");if(!b){b=new Fx.Reveal(this);this.store("reveal",b)}return b}};Element.Properties.dissolve=Element.Properties.reveal;Element.implement({reveal:function(b){this.get("reveal").setOptions(b).reveal();return this},dissolve:function(b){this.get("reveal").setOptions(b).dissolve();return this},nix:function(b){var c=Array.link(arguments,{destroy:Type.isBoolean,options:Type.isObject});this.get("reveal").setOptions(b).dissolve().chain(function(){this[c.destroy?"destroy":"dispose"]()}.bind(this));return this},wink:function(){var c=Array.link(arguments,{duration:Type.isNumber,options:Type.isObject});var b=this.get("reveal").setOptions(c.options);b.reveal().chain(function(){(function(){b.dissolve()}).delay(c.duration||2000)})}})})();Fx.Move=new Class({Extends:Fx.Morph,options:{relativeTo:document.body,position:"center",edge:false,offset:{x:0,y:0}},start:function(a){var b=this.element,c=b.getStyles("top","left");if(c.top=="auto"||c.left=="auto"){b.setPosition(b.getPosition(b.getOffsetParent()))}return this.parent(b.position(Object.merge({},this.options,a,{returnPos:true})))}});Element.Properties.move={set:function(a){this.get("move").cancel().setOptions(a);return this},get:function(){var a=this.retrieve("move");if(!a){a=new Fx.Move(this,{link:"cancel"});this.store("move",a)}return a}};Element.implement({move:function(a){this.get("move").start(a);return this}}); /* --- description: CwCrop authors: - Mario Fischer (http://www.chipwreck.de/blog/) license: - MIT-style license requires: core/1.2.3: '*' more/1.2.3: 'Drag.*' provides: - CwCrop version: 0.95 ... */ CwCrop = new Class({ Implements: [Options,Events], options: { minsize: {x: 60, y: 60}, // minimal size of the resulting image maxsize: {x: 200, y: 200}, // maximal size of the resulting image originalsize: {x: 1, y: 1}, // size of the original image (if the crop area uses a smaller version) fixedratio: false, // if set to a number, use this as a fixed ratio (and ignore maxratio) maxratio: {x: 2, y: 2}, // maximum ratio x, y initialposition: {x: 10, y: 10}, // initial position (in the crop area) initialmax: false, // extend the crop area initially to the maximum size classactive: "active", // css classname for the crop frame if the user moves/resizes cropframe: "cropframe", // css id of the crop frame imgframe: "imglayer", // css id of the image frame cropdims: "cropdims", // css id for the crop dimensions (leave empty to disable showing dimensions) cropbtn: "cropbtn", // css id for an addition button (leave empty to disable) draghandle: "draghandle", // css id for the dragging handle resizehandle: "resizeHandleXY", // css id for the resizing handle onCrop: function() {} // function to execute if the user crops }, initialize: function(options) { this.setOptions(options); if (!$(this.options.cropframe) || !$(this.options.imgframe)) { return; } // calc initial limits and scaling this.elemsize = $(this.options.imgframe).getSize(); if (this.elemsize.x === 0) { this.elemsize = $(this.options.imgframe).getOffsetParent().getSize(); } this.orig_to_scaled = {x: 1, y: 1}; if (this.options.originalsize.x > 1 && this.options.originalsize.y > 1) { this.orig_to_scaled.x = this.options.originalsize.x / this.elemsize.x; this.orig_to_scaled.y = this.options.originalsize.y / this.elemsize.y; } this.options.maxsize.x = ( this.options.maxsize.x * (1/this.orig_to_scaled.x) ).limit(1, this.elemsize.x-2); this.options.maxsize.y = ( this.options.maxsize.y * (1/this.orig_to_scaled.y) ).limit(1, this.elemsize.y-2); this.options.minsize.x = ( this.options.minsize.x * (1/this.orig_to_scaled.x) ).limit(1, this.elemsize.x-2); this.options.minsize.y = ( this.options.minsize.y * (1/this.orig_to_scaled.y) ).limit(1, this.elemsize.y-2); this.limits = { x:[this.options.minsize.x, this.options.maxsize.x], y:[this.options.minsize.y, this.options.maxsize.y] }; // init crop frame if (this.options.initialmax) { $(this.options.cropframe).setStyle("top", 0); $(this.options.cropframe).setStyle("left", 0); $(this.options.cropframe).setStyle("width", this.limits.x[1].toInt()); $(this.options.cropframe).setStyle("height", this.limits.y[1].toInt()); } else { $(this.options.cropframe).setStyle("top", this.options.initialposition.y); $(this.options.cropframe).setStyle("left", this.options.initialposition.x); $(this.options.cropframe).setStyle("width", this.limits.x[0].toInt()); $(this.options.cropframe).setStyle("height", this.limits.y[0].toInt()); } if (this.options.fixedratio) { $(this.options.cropframe).setStyle("width", $(this.options.cropframe).getStyle("height").toInt() * this.options.fixedratio); } this.updateCropDims($(this.options.cropframe)); this.recalcResize($(this.options.cropframe)); this.myMove = new Drag.Move($(this.options.cropframe), { style: true, precalculate: true, snap: 1, grid: false, container: $(this.options.imgframe), includeMargins: true, checkDroppables: false, handle: $(this.options.draghandle), onStart: function(el) { el.addClass(this.options.classactive); }.bind(this), onDrag: function(el) { this.moveBgImage(el); this.updateCropDims(el, true); }.bind(this), onComplete: function(el) { el.removeClass(this.options.classactive); this.updateCropDims(el); this.recalcResize(el); }.bind(this) }); this.moveBgImage($(this.options.cropframe)); this.myResizeXY = $(this.options.cropframe).makeResizable({ style: true, precalculate: true, snap: 1, grid: false, handle: $(this.options.resizehandle), limit: this.limits, onStart: function(el) { el.addClass(this.options.classactive); }.bind(this), onDrag: function(el, event) { this.checkRatio(el, event); this.updateCropDims(el); }.bind(this), onComplete: function(el) { el.removeClass(this.options.classactive); }.bind(this) }); if ($(this.options.cropbtn)) { $(this.options.cropbtn).addEvent('click', function() { this.doCrop(); }.bind(this)); } }, createHtml: function(el, imgname) { /*
*/ }, moveBgImage: function(el) { el.setStyle("background-position","-" + (el.getStyle("left").toInt()) + "px " + "-" + (el.getStyle("top").toInt()) + "px"); }, checkRatio: function(el, event) { var newwidth = 0; var newheight = 0; var ratio = el.getStyle("width").toInt() / el.getStyle("height").toInt(); if (this.options.fixedratio) { if (ratio != this.options.fixedratio) { newwidth = el.getStyle("height").toInt() * this.options.fixedratio; } } else if (event.shift && ( (!this.options.maxratio.x && !this.options.maxratio.y) || (!this.options.maxratio.x && this.options.maxratio.y >= 1) || (this.options.maxratio.x >= 1 && !this.options.maxratio.y) || (this.options.maxratio.x >= 1 && this.options.maxratio.y >= 1) )) { if (ratio > 1) { newwidth = el.getStyle("height").toInt(); } else if (ratio < 1) { newheight = el.getStyle("width").toInt(); } } else { if (ratio > 1 && ratio > this.options.maxratio.x) { newwidth = el.getStyle("height").toInt() * this.options.maxratio.x; } else if (ratio < 1 && ratio < (1/this.options.maxratio.y)) { newheight = el.getStyle("width").toInt() * this.options.maxratio.y; } } if (newwidth > this.limits.x[0] && newwidth < this.limits.x[1]) { el.setStyle("width", newwidth); } else if (newheight > this.limits.y[0] && newheight < this.limits.y[1]) { el.setStyle("height", newheight); } else if (this.options.fixedratio && ratio != this.options.fixedratio) { el.setStyle("height", el.getStyle("width").toInt() / this.options.fixedratio); } }, recalcResize: function(el) { this.limits.x[1] = this.elemsize.x - ( el.getStyle("left").toInt() ) - 2; this.limits.y[1] = this.elemsize.y - ( el.getStyle("top").toInt() ) - 2; this.limits.x[1] = Math.round( Math.min( this.limits.x[1], this.options.maxsize.x ) ); this.limits.y[1] = Math.round( Math.min( this.limits.y[1], this.options.maxsize.y ) ); if (this.myResizeXY) { this.myResizeXY.options.limit = this.limits; } }, updateCropDims: function(el, displayPosition) { if (!$(this.options.cropdims)) { return; } if (displayPosition) { xresized = Math.round( el.getStyle("left").toInt() * this.orig_to_scaled.x ); yresized = Math.round( el.getStyle("top").toInt() * this.orig_to_scaled.y ); out = xresized + ", " + yresized; } else { xresized = Math.round( el.getStyle("width").toInt() * this.orig_to_scaled.x ); yresized = Math.round( el.getStyle("height").toInt() * this.orig_to_scaled.y ); out = xresized + " x " + yresized; } $(this.options.cropdims).set('html', out); }, doCrop: function() { var el = $(this.options.cropframe); var x = Math.round( el.getStyle("left").toInt() * this.orig_to_scaled.x ); var y = Math.round( el.getStyle("top").toInt() * this.orig_to_scaled.y ); var w = Math.round( el.getStyle("width").toInt() * this.orig_to_scaled.x ); var h = Math.round( el.getStyle("height").toInt() * this.orig_to_scaled.y ); if (x >= 0 && y >= 0 && h >= this.options.minsize.y && w >= this.options.minsize.x) { this.fireEvent('onCrop',{'x':x,'y':y,'w':w,'h':h}); } } }); /** * Framework for forms. * THIS FILE IS STILL IN PROGRESS. */ EOL.namespace('framework.form'); /** * Async Form. Takes a form ID and options hash as args. * Sets up the handleSubmit function to Async the form to server, and handle response (RequestMsg format) * Designed to take care of dynamically adding the 't' input, setting new form tokens, smartly handling * errors in the RequestMsg format using formUtil or infoDialogs if available, and handling confirm * urls when available. * Options: * async - if false, submits the form the old fashioned way. Only really useful for form.dialog * hidden - if true, skips all visual code, like showing wait cursor * errorEl - if set, assume this is a flowUtil error Element * mainEl - if set, this marks the top-level ID for this form. Used for enable/disableElems, error clearing */ EOL.framework.form.async = function(formEl, opts){ this.formEl = formEl; this.form = $(this.formEl); var defaults = { async: true, hidden: false, errorEl: null, confirmEl: null, mainEl: null, method: 'post' }; EOL.utility.mergeObjects(defaults, opts); this.options = defaults; this.loading = false; // Used to tell if we're still waiting for content this.initRequest = false; this.setOptions = function(opts){ EOL.utility.mergeObjects(this.options, opts); }; this.beforeError = function(response){}; this.afterError = function(response){}; // This onsubmit code prevents the user from submitting the form the old fashioned way if( this.form ) { var me = this; this.form.onsubmit = function(e){ e.preventDefault(); me.handleSubmit(); }; } }; /** Validates the form. Needs to be overriden to do anything useful **/ EOL.framework.form.async.prototype.validate = function() { return true; }; /** Submits the form **/ EOL.framework.form.async.prototype.handleSubmit = function() { // error clearing if( this.options.mainEl && typeof clearFormErrorsAll == 'function' ){ clearFormErrors(this.options.mainEl); } if( this.options.confirmEl ) { $(this.options.confirmEl).addClass('displayNone'); } if( typeof clearFormErrorsAll == 'function' && this.options.errorEl ){ clearFormErrorsAll(this.options.errorEl); } else if( this.options.errorEl ) { $(this.options.errorEl).addClass('displayNone'); } if( !this.validate() ){ return false; } if( !this.options.async ){ this.form.submit(); return true; } if( !this.options.hidden ) disableElems( $(this.options.mainEl) ); var async = this; var options = { method : this.options.method, onSuccess: function(req) {async.handleAjaxSuccess(req);}, onFailure: function(req) {async.handleAjaxFailure(req);}, onComplete: function(req) {async.handleAjaxComplete(req);} }; if( MooTools.version == '1.11' ){ this.form.send(options); } else { if(!this.initRequest) { this.form.set('send', options); this.initRequest = true; } this.form.send(); } this.loading = true; return true; }; /** For use in href=javascript: fashion. Has no return so the link doesn't activate **/ EOL.framework.form.async.prototype.handleSubmitHref = function() { this.handleSubmit(); }; /** AJAX success: determine process result **/ EOL.framework.form.async.prototype.handleAjaxSuccess = function(res) { this.responseText = res; this.loading = false; if( !res || res.indexOf('{') == -1 ) res = '{}'; var response = eval('('+ res +')'); if( !response || !response.status ){ this.handleFailure(); return; } if( response.token ) EOL.framework.form.resetTokens(response.token); if( response.status == 'success') { this.handleSuccess(response); } else { this.handleError(response); } }; /** AJAX Failure: throw an error **/ EOL.framework.form.async.prototype.handleAjaxFailure = function(res) { this.loading = false; // This will happen if the user navigates while the request is still running if( res.readyState == 4 && res.status == 0 ) return; // We have a legitimate error: display it this.handleFailure(res); this.handleAjaxComplete(res); // failure case does not automatically call this like it should; mootools 1.11 issue }; EOL.framework.form.async.prototype.handleAjaxComplete = function(res){}; /** AJAX + process success **/ EOL.framework.form.async.prototype.handleSuccess = function(response) { if( response.data && response.data.confirmURL ){ // Confirm URL window.location.href = response.data.confirmURL; } else if( response.data && response.data.confirmElemId && response.data.confirmTitle && response.data.confirmText ) { enableElems( $(this.options.mainEl) ); EOL.util.dialog.createConfirmBox( response.data.confirmElemId, response.data.confirmTitle, response.data.confirmText ); } else if( response.data && response.data.confirmElemId && response.data.confirmElemId == this.options.confirmEl ) { enableElems( $(this.options.mainEl) ); $(response.data.confirmElemId).removeClass('displayNone'); } else if( response.data && response.data.confirmText ){ // Confirmation in the response enableElems( $(this.options.mainEl) ); if( typeof showInfoDialogText == 'function' ){ // Info dialog: preferred showInfoDialogText( response.data.confirmTitle, response.data.confirmText, 'INFO' ); } else { alert(response.data.confirmTitle +': '+ response.data.confirmText); } } else { if( !this.options.hidden ) enableElems( $(this.options.mainEl) ); this.handleSuccessDefault(response); } }; // For overriding. Be warned that if your dialog is not hidden, it will auto-call enableElems above. Consider // overriding handleSuccess proper if you don't want that. EOL.framework.form.async.prototype.handleSuccessDefault = function(response) { if( !this.options.hidden ) window.location.reload(true); }; /** AJAX failure **/ EOL.framework.form.async.prototype.handleFailure = function(){ var errorMsgs = new Array(); errorMsgs[0] = "There was an error communicating with Elance."; var response = { errorTitle : "We're Sorry", errorMsgs: errorMsgs }; this.handleError(response); }; /** AJAX or process error **/ EOL.framework.form.async.prototype.handleError = function(response) { if( this.options.hidden ) return; enableElems( $(this.options.mainEl) ); this.beforeError(response); var errorTitle = (response.errorTitle ? response.errorTitle : 'Please correct the following'); // If we have an errorEl and no errorMsgsEl was set in the response, use ours if( this.options.errorEl && !response.errorMsgsEl ) response.errorMsgsEl = this.options.errorEl; if( typeof flowDisplayErrors == 'function' && response.errorMsgsEl && $(response.errorMsgsEl) ){ // Flow util: preferred this.options.errorEl = response.errorMsgsEl; flowDisplayErrors(response); } else if( typeof flowDisplayErrorsDialogText == 'function' ){ // Dialog if available flowDisplayErrorsDialogText( response, errorTitle ); } else if( typeof flowDisplayErrorsInfoDialogText == 'function' ){ // Info Dialog if available flowDisplayErrorsInfoDialogText( response, errorTitle, 'WARN' ); } else { this.showErrors(response, errorTitle); } this.afterError(response); }; EOL.framework.form.async.prototype.showErrors = function(response, errorTitle) { // Alert msg by default var msg = ''; for( var i = 0; i < response.errorMsgs.length; i++ ) { msg += (i == 0 ? '' : ', ') + response.errorMsgs[i]; } if( typeof EOL.dialog == 'function' ){ var opts = {width: "350"}; if( this.dialog && this.dialog.optons && this.dialog.options.className ) { opts.className = this.dialog.options.className; } else if( this.options && this.options.dialogClassName ) { opts.className = this.options.dialogClassName; } this.errorDialog = new EOL.dialog([errorTitle,msg], opts); this.errorDialog.show(); } else if( typeof showInfoDialog == 'function' ){ showInfoDialogText(errorTitle, msg, 'WARN'); } else { alert(errorTitle +': '+ msg); } }; /** * Like async, but gets an HTML response from the server that gets written into contentEl. * * controls: * waiting - allows the caller to make this wait before hiding the loadingEL. Useful for synchronizing events * * Options: * loadingEl - specify an element that is shown while loading * onComplete - function to call when we're done. Useful for synchronizing */ EOL.framework.form.asyncContent = function( formEl, contentEl, opts ){ var me = this; var defaults = { loadingEl: null, onComplete: null, mainEl: contentEl }; EOL.utility.mergeObjects(defaults, opts); EOL.framework.form.asyncContent.superclass.constructor.call(this, formEl, defaults); this.contentEl = contentEl; this.waiting = false; // Used to make the showLoading wait for some other event // set our loading flag, hideLoading, and set the response in page. Call oncomplete this.handleAjaxSuccess = function(response){ this.responseText = response; this.loading = false; this.hideLoading(); // If we get a JSON response, handle using parent if( response && response.replace(/^\s*/, "").indexOf('{') == 0 ){ EOL.framework.form.asyncContent.superclass.handleAjaxSuccess.call(this, response); return; } if( !response ){ this.handleFailure(); return; } this.handleSuccess( {data: {html: response}} ); }; this.handleSuccess = function(response){ if( response && response.data && response.data.html ){ $(this.contentEl).innerHTML = response.data.html; } // If we have an onComplete and we aren't waiting, call it if( !this.waiting ) this.onComplete(response); }; // Show the loadingEl and hide the contentEl this.showLoading = function(){ if( this.options.loadingEl ){ $(this.options.loadingEl).removeClass('displayNone'); $(this.contentEl).addClass('displayNone'); } if( !this.options.hidden ) disableElems( $(this.options.mainEl) ); }; // hide the loadingEl and show the contentEl this.hideLoading = function(){ // If we are waiting or still loading, do not do this and let the caller know if( this.waiting || this.loading ) return false; if( this.options.loadingEl ){ $(this.options.loadingEl).addClass('displayNone'); $(this.contentEl).removeClass('displayNone'); } // Have to call this here because of the waiting case if( !this.options.hidden ) enableElems( $(this.options.mainEl) ); return true; }; // To be executed after complete this.onComplete = function(){}; if( this.options.onComplete ) this.onComplete = this.options.onComplete; }; EOL.utility.extend(EOL.framework.form.asyncContent, EOL.framework.form.async); // Show loading on submit EOL.framework.form.asyncContent.prototype.handleSubmit = function(){ if( EOL.framework.form.asyncContent.superclass.handleSubmit.call(this) ){ this.showLoading(); }; }; /** * Form Dialog class. Takes the dialog ID, form ID (MUST BE INSIDE THE DIALOG), and options hash * Extends the async form class. * Contains a EOL.dialog class for the dialog UI * Call handleSubmit to submit the dialog. Override handleSubmit for custom behaviors * * Options: (Also uses EOL.dialog options) * inlineSuccess - set to true if success shown inside dialog. then it won't hide on success * inlineErrorEl - set to ID if error shown inside dialog. then it won't hide on error */ EOL.framework.form.dialog = function( dialogEl, formEl, opts ){ var me = this; var defaults = { // defaults inlineSuccess: false, inlineErrorEl: false, width : "430", mainEl: dialogEl }; EOL.utility.mergeObjects(defaults, opts); if( defaults.inlineErrorEl && !defaults.errorEl ){ defaults.errorEl = defaults.inlineErrorEl; } EOL.framework.form.dialog.superclass.constructor.call(this, formEl, defaults); this.innerElement = $(dialogEl); this.beforeShow = function(){}; this.afterShow = function(){}; this.beforeHide = function(){}; this.afterHide = function(){}; // Create our dialog to handle UI this.dialog = new EOL.dialog($(dialogEl), defaults); // Override the default close to call hide this.dialog.eventHide = function(){ me.hide(); }; }; EOL.utility.extend(EOL.framework.form.dialog, EOL.framework.form.async); EOL.framework.form.dialog.prototype.show = function(){ this.beforeShow(); this.dialog.show(); this.afterShow(); }; EOL.framework.form.dialog.prototype.hide = function(){ this.beforeHide(); this.dialog.hide(); this.afterHide(); }; EOL.framework.form.dialog.prototype.update = function(){ this.beforeShow(); this.dialog.update($(this.dialogEl).innerHTML); $(this.dialogEl).innerHTML = ''; this.afterShow(); }; // If you override this, be sure to call hide when necessary. EOL.framework.form.dialog.prototype.handleSuccess = function(res){ if( !this.options.inlineSuccess ) this.dialog.hide(); EOL.framework.form.dialog.superclass.handleSuccess.call(this, res); }; // If you override this, be sure to call hide when necessary. EOL.framework.form.dialog.prototype.handleError = function(res){ if( this.options.inlineErrorEl ) res.errorMsgsEl = this.options.inlineErrorEl; else this.dialog.hide(); EOL.framework.form.dialog.superclass.handleError.call(this, res); }; /** * an async content + dialog mixed together. * The asyncContent is used to load the dialog contents * This object extends dialog and functions just like the dialog except for the load */ EOL.framework.form.asyncDialog = function( aFormEl, aOpts, dialogEl, dFormEl, dOpts ){ var me = this; this.asyncContent = new EOL.framework.form.asyncContent( aFormEl, dialogEl, aOpts ); this.asyncContent.owner = this; this.asyncContent.onComplete = function(response){ me.initSelf(); me.show(); if( aOpts.onComplete ) aOpts.onComplete.call(this, response); }; // Save these args for later this.dialog = null; this.dialogEl = dialogEl; this.dFormEl = dFormEl; this.dOpts = dOpts; this.loaded = false; this.initSelf = function(){ EOL.framework.form.asyncDialog.superclass.constructor.call(this, this.dialogEl, this.dFormEl, this.dOpts); this.loaded = true; this.afterInitSelf(); }; this.afterInitSelf = function(){}; this.unload = function(){ this.loaded = false; }; }; EOL.utility.extend(EOL.framework.form.asyncDialog, EOL.framework.form.dialog); // Handle loading the dialog if it hasn't been already EOL.framework.form.asyncDialog.prototype.show = function(){ if( this.loaded ){ if(this.dOpts.id && $(this.dOpts.id)) { this.update(); } else { EOL.framework.form.asyncDialog.superclass.show.call(this); } } else { this.asyncContent.handleSubmit(); } }; // These next 2 override clear out the dialog if it is closed EOL.framework.form.asyncDialog.prototype.hide = function(){ if( !this.loaded ) return; this.unload(); EOL.framework.form.asyncDialog.superclass.hide.call(this); }; EOL.framework.form.asyncDialog.prototype.handleSuccess = function(res){ this.unload(); EOL.framework.form.asyncDialog.superclass.handleSuccess.call(this, res); }; // util to reset all tokens in the page EOL.framework.form.resetTokens = function(newToken){ EOL.utility.resetFormTokens(newToken, 'token'); }; EOL.profile.editCountry = function() { var confirm = new EOL.dialog(['Country Verification','You must pass the Elance Admission Test and verify your phone number before your country can be verified.'], {position: 'fixed', modal:true, width: 300, close:true}); confirm.show(); } EOL.namespace('editProfile'); window.addEvent('domready', function(){ if ($('baseRate')) { EOL.wizard.updateBaseRate($('txnFee').value, 'baseRate', 'minRate', 'minRate'); } var myURI = new URI(document.URL); if (myURI.getData('promo')) { if (!EOL.editProfile.tieConnectDialog) { new Request({ url: '/register/contractor/profileConnects', method: 'get', onSuccess: function(response) { EOL.editProfile.tieConnectDialog = new EOL.dialog(response,{'width': 540}); EOL.editProfile.tieConnectDialog.show(); } }).send(); document.addEvent('click:relay(#profileConnectsDialog .close-btn)', function(){ EOL.editProfile.tieConnectDialog.hide(); }); } else { EOL.editProfile.tieConnectDialog.show(); } } }); EOL.editProfile.handleCityStateCountry = function(inputElement){ if(inputElement.value.length >= 3){ console.log(inputElement.value); var jsonRequest = new Request.JSON({url: '/php/preferences/main/locationAutoSuggest.php', onSuccess: function(rslt){ console.log(rslt); EOL.editProfile.cityStateCountryAutoSuggest(rslt.data.list); }}).get({'query': inputElement.value, 'method': 'citystatecountryAutolist'}); } } EOL.editProfile.cityStateCountryAutoSuggest = function(list){ var acdd = $('cscAutoComplete'); var cscTextbox = $('citystatecountry'); acdd.position({ relativeTo: cscTextbox, position: 'bottomLeft', edge: 'upperLeft' }); acdd.empty(); var listlength = list.length; for (var i = 0; i < listlength; i++) { var option = new Element('div',{'text':list[i].text}); option.set('id','dd'+i); //option.set('style',"cursor:pointer;cursor:hand;border-style:solid; border-width:1px; border-color:#0067b4; width: 300px; padding-left: 5px; padding-top: 5px; padding-bottom: 15px; border:1px; font-size:12px; background-color:#ffffff;"); option.set('class','interstitial_suggest_entry'); option.set('onclick',"EOL.editProfile.cityStateCountryAutoSuggestSelect(this.id);"); option.set('onmouseover',"EOL.editProfile.onAutoSuggestdivhover(this.id, 1);"); option.set('onmouseout',"EOL.editProfile.onAutoSuggestdivhover(this.id, 0);"); option.inject(acdd); } } EOL.editProfile.cityStateCountryAutoSuggestSelect = function(selectedElement){ //selectElement.style.visibility = 'hidden'; var acdd = $('cscAutoComplete'); var ddElement = $(selectedElement); var cscTextbox = $('citystatecountry'); cscTextbox.value = ddElement.get('text'); acdd.empty(); } EOL.editProfile.onAutoSuggestdivhover = function(elemId, isHovering){ var ddElement = $(elemId); var bgcolor = '#ffffff'; var color = '#000000'; if(isHovering == 1){ bgcolor = '#0067b4'; color = '#ffffff'; } if (ddElement != null) { ddElement.setStyle('background-color',bgcolor); ddElement.setStyle('color',color); } } EOL.editProfile.submitEditForm = function(action, isIdVerified) { /* If the profile is Id Verified and changes are being attempted, then check if the first name/last name got affected. If yes, then throw the warning modal else continue with submission. */ var throwWarningModal = false; if (isIdVerified){ // Check if the first name or the last name got affected. firstNameVerOrigLC = $('firstNameVerOrig').get('value').toLowerCase(); lastNameVerOrigLC = $('lastNameVerOrig').get('value').toLowerCase(); /* in the case of business plans the first/last name are not displayed * therefore we need to insure the element exist before attempting * to obtain it's value */ if ($('firstName') !== null){ firstNameNewLC = $('firstName').get('value').toLowerCase(); } else{ firstNameNewLC = firstNameVerOrigLC; } //check if the last name has been changed if ($('lastName') !== null){ lastNameNewLC = $('lastName').get('value').toLowerCase(); } else{ lastNameNewLC = lastNameVerOrigLC; } var firstOrLastNameAffected = ((firstNameVerOrigLC != firstNameNewLC) || (lastNameVerOrigLC != lastNameNewLC)); throwWarningModal = firstOrLastNameAffected; } if (throwWarningModal) { // throw the warning modal. EOL.idVerifLooseWarningModal.js.open(function() { EOL.editProfile.submitEditFormInternal(action); }); } else { EOL.editProfile.submitEditFormInternal(action); } } EOL.editProfile.submitEditFormInternal = function(action) { $('editProfileError').style.display = 'none'; var postData = $('editProfileForm').toQueryString(); postData += '&action=' + action; if (action == 'saveGeneralInfo' && $('companyName') && $('companyName').disabled) { postData += '&companyName='+$('companyName').value; } disableElems($('pedit-buttons')); var options = { url: '/php/profile/main/editProfileAHR.php?t=' + getDateTime(), method: 'post', data: postData, onSuccess: EOL.editProfile.handleSuccess, onFailure: function() { alert('There was an error processing your request. Please refresh and try again.'); } }; curAsyncReq = new Request(options); curAsyncReq.send(); } EOL.editProfile.handleSuccess = function( obj ) { //-- read JSON data var response = eval('(' + obj + ')'); if( response.status == 'success' ) { window.location = response.data.redirectUrl; } else if( response.status == 'error' ) { enableElems($('pedit-buttons')); var errorArr = response.errorMsgs; $('editProfileErrMsg').innerHTML = ''; for( var i = 0; i < errorArr.length; i++ ) { $('editProfileErrMsg').innerHTML += '
  • ' + errorArr[i] + '
  • '; } $('editProfileError').style.display = ''; scrollTo(0,0); } } EOL.editProfile.checkCountry = function() { var countryHidden = $('countryHidden'); if( countryHidden.value == 'US' || ($('country') && $('country').value == 'US') ) { document.getElementById('state').style.display = ''; document.getElementById('state2').style.display = 'none'; } else { document.getElementById('state').style.display = 'none'; document.getElementById('state2').style.display = ''; } } EOL.editProfile.checkCountryTip = function() { var country = $('country').get('value'); if(country == '00') $('country-tip').removeClass('displayNone'); else $('country-tip').addClass('displayNone'); } EOL.editProfile.handleVerifyOptionClick = function () { if($('verifyOption').checked) $('confrLocationDetails').style.display = 'block'; else $('confrLocationDetails').style.display = 'none'; } // Sets add another parameter before handling the save credential action EOL.editProfile.setAddAnotherFlag = function () { $('addAnother').value =true; } EOL.editProfile.updateTotal = function() { var inputs = document.getElementsByTagName('input'); var total = 0; for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == 'checkbox' && inputs[i].id.substring(0,4)=='cred' && inputs[i].checked) { var charge = $('price'+ inputs[i].id.substring(4)).innerHTML; total += parseFloat(charge); } } $('totalAmount1').innerHTML = '$' + total.toFixed(2); $('totalAmount2').innerHTML = '$' + total.toFixed(2); $('totalAmount').value = total.toFixed(2); } EOL.editProfile.initCompanyName = function() { EOL.editProfile.firstName = $('firstName').value.trim(); EOL.editProfile.lastName = $('lastName').value.trim(); } EOL.editProfile.setCompanyName = function() { var companyName = ''; if ($('firstName')) companyName += $('firstName').value.trim().capitalize(); if ($('lastName')) { var lastName = $('lastName').value.trim(); if ($('showInitialOnly').checked) { lastName = lastName.charAt(0).toUpperCase()+'.'; } companyName += ' '+lastName.capitalize(); } $('companyName').value = String(companyName).substr(0, 100); } EOL.editProfile.confirmReg = function() { if (!$('confirmReg')) return; new EOL.dialog($('confirmReg').get('html'), { position:'fixed', modal:true, className:'confirmRegDialog' }).show(); } EOL.editProfile.getStartedVideoDialog = null EOL.editProfile.openVideo = function(noBack) { if (!$('getStartedVideo')) return false; if (!EOL.editProfile.getStartedVideoDialog) { EOL.editProfile.getStartedVideoDialog = new EOL.dialog( $('getStartedVideo').get('html'), { position:'fixed', modal:true, className:'getStartedVideoDialog' } ); $('getStartedVideo').set('html', ''); } EOL.editProfile.getStartedVideoDialog.show(); if (noBack) { $('videoShowBack').addClass('displayNone'); } else { $('videoShowBack').removeClass('displayNone'); } return false; } EOL.editProfile.closeVideo = function() { EOL.editProfile.getStartedVideoDialog.hide(); return false; } EOL.editProfile.closePopups = function() { EOL.editProfile.getStartedVideoDialog.hide(); return false; } EOL.editProfile.earningSettings = function(){ if($('privateTeamEarnings')){ if($('privateEarnings') && $('privateEarnings').checked){ $('privateTeamEarnings').disabled = true; $('privateTeamEarnings').checked = true; } else { $('privateTeamEarnings').disabled = false; } } } function openTip(id) { closeTips('tip'); $(id).removeClass('displayNone'); } function closeTip(id) { $(id).addClass('displayNone'); } function closeTips(cl) { $$('.'+cl).each(function(v){v.addClass('displayNone')}); } /** * Displays the top header message for the edit profile page. * * @param string messageType Type of message - can be either 'Error' or 'Confirm'. * @param string header Message header. * @param string bodyText Message body. * @return */ EOL.editProfile.showHeaderMessage = function(messageType, header, bodyText) { var className = "", closeBtn = ""; if (messageType == "Error") { className = "errorBox"; } else if (messageType == "Confirm") { className = "confirmBox"; closeBtn = "
    "; } var innerHtml = "
    "+closeBtn+" " + header + " " + bodyText + "
    "; /* var messageBox = new Element('div', {class: 'confirmBox'}); var headerSpan = new Element('span', {class: 'header'}); headerSpan.set('text', header); */ $('provider-profile-message').set('html', innerHtml); $('provider-profile-message').removeClass('displayNone'); /* Hide the top banner as it is moving real stuff down a lot */ $('eol-banner').addClass('displayNone'); /* Add a handler to hide the message box and unhide the eol-banner div box. */ } /* Opens the Id Verify request modal which shows the details of the profile to be verified */ EOL.namespace('idVerifRequestModal'); EOL.idVerifRequestModal.dialog = null; EOL.idVerifRequestModal.open = function() { if (EOL.idVerifRequestModal.dialog == null) { var content = $(EOL.idVerifRequestModal.constants.INIT_MODAL_CONTENT).innerHTML; // remove the original modal content element. $(EOL.idVerifRequestModal.constants.INIT_MODAL_CONTENT).dispose(); EOL.idVerifRequestModal.dialog = new EOL.dialog(content, {position: 'fixed', width:500, modal:true, close:true}); } EOL.idVerifRequestModal.dialog.show(); } EOL.idVerifRequestModal.close = function() { EOL.idVerifRequestModal.dialog.hide(); } // Modal Element id constants. EOL.idVerifRequestModal.constants = { ERR_BOX_TOS : 'id-verif-modal-error-box-tos', ERR_BOX : 'id-verif-modal-error-box', ACCEPT : 'id-verif-accept', INIT_MODAL_CONTENT: 'id-verif-initiate-modal-content', DISPLAY_NONE_CLASS : 'displayNone', EXT_ID_VER_REDIRECT_STR : 'idVerifRedirect', RESP_DATA_STR : 'data' }; EOL.idVerifRequestModal.unknownErrStr = 'There was an error processing your request. Please refresh and try again.'; EOL.idVerifRequestModal.submit = function() { // Hide the accept TOS error. $(EOL.idVerifRequestModal.constants.ERR_BOX_TOS).addClass(EOL.idVerifRequestModal.constants.DISPLAY_NONE_CLASS); // Hide the accept error box. $(EOL.idVerifRequestModal.constants.ERR_BOX).addClass(EOL.idVerifRequestModal.constants.DISPLAY_NONE_CLASS); /* Check that the checkbox is ticked */ if (!$(EOL.idVerifRequestModal.constants.ACCEPT).checked) { // Show the accept TOS error. $(EOL.idVerifRequestModal.constants.ERR_BOX_TOS).removeClass(EOL.idVerifRequestModal.constants.DISPLAY_NONE_CLASS); return; } disableElems($('id-verif-continue-button-parent')); /* Call the token generation here */ var url = '/php/profile/main/generateIdVerifReqAHR.php?t=' + getDateTime() + '&mode=GetNewIdVerToken&verbose=false'; var options = { url: url, method: 'get', onSuccess: EOL.idVerifRequestModal.handleSubmitSuccess, onFailure: function() { EOL.idVerifRequestModal.showErrorMessage(EOL.idVerifRequestModal.unknownErrStr); }, onTimeout: function() { EOL.idVerifRequestModal.showErrorMessage(EOL.idVerifRequestModal.unknownErrStr); } }; curAsyncReq = new Request(options); curAsyncReq.send(); } EOL.idVerifRequestModal.handleSubmitSuccess = function(responseText) { var response = JSON.decode(responseText); if (!(EOL.idVerifRequestModal.constants.RESP_DATA_STR in response)) { EOL.idVerifRequestModal.showErrorMessage(EOL.idVerifRequestModal.unknownErrStr); return; } var data = response[EOL.idVerifRequestModal.constants.RESP_DATA_STR]; // Check that status is success. // check for the generated token and redirect to Aristotle if (data == null || !(EOL.idVerifRequestModal.constants.EXT_ID_VER_REDIRECT_STR in data)) { EOL.idVerifRequestModal.showErrorMessage(EOL.idVerifRequestModal.unknownErrStr); return; } var idVerifRedirect = data[EOL.idVerifRequestModal.constants.EXT_ID_VER_REDIRECT_STR]; // redirect now. window.location = idVerifRedirect; } EOL.idVerifRequestModal.showErrorMessage = function(mesg) { // Show the error div. $(EOL.idVerifRequestModal.constants.ERR_BOX).removeClass(EOL.idVerifRequestModal.constants.DISPLAY_NONE_CLASS); $(EOL.idVerifRequestModal.constants.ERR_BOX).set('html', mesg); } EOL.namespace('trust'); var phoneVerifPanel; // Panel for verif function phoneVerifLoad(mode){ if (!phoneVerifPanel) {initPhoneVerif(); } phoneVerifPanel.show(); // reload switch (mode) { case 'change': var tail='state=change'; break; default: var tail='r+'+Math.round(Math.random*10000); break; } var iFrame = new Element('iframe', { src: '\/phoneverififrame?'+tail, scrolling: "no", frameBorder: 0, id: 'phoneVerifPanelIframe1', styles: { width: '480px', }, events: { load: function() { $('phoneVerifPanelIframeLoading').addClass('displayNone'); } } }); // Load it into panel $$('#phoneVerifDialog #phoneVerifPanelBody')[0].appendChild(iFrame); } function closePhoneVerifPanel(reload){ if (reload) { location.reload(); } phoneVerifPanel.hide(); } function initPhoneVerif(){ phoneVerifPanel = new EOL.dialog($('phoneVerifPanelDiv'), {width: 480, position: 'fixed', modal:true, close:true, id: 'phoneVerifDialog' }); phoneVerifPanel.afterHide = function() { // We need to do this on close for IE to cooperate! document.getElementById('phoneVerifPanelBody').removeChild($('phoneVerifPanelIframe1')); $('phoneVerifPanelIframeLoading').removeClass('displayNone'); }; } function resizeIFrame(height){ $('phoneVerifPanelIframe1').setStyle('height', height); phoneVerifPanel.resize(); } function advanceTrain (response) { if (response.status == 'success') { window.location.href = response.data.returnUrl; } } function handleSuccess( obj) { var response = eval('(' + obj + ')'); if( response.status == 'success' ) { advanceTrain(response); } else if ( response.status == 'error' ) { displayErrors( response ); } } function handleError(obj) { } function handleNoThanksSuccess (obj) { var response = eval('(' + obj + ')'); if( response.status == 'success' ) { advanceTrain(response); } else if ( response.status == 'error' ) { displayErrors( response ); } } function handleLogoOptSuccess(obj) { var response = eval('(' + obj + ')'); if( response.status == 'success' ) { window.location.reload(); } } function displayErrors( response) { $(response.errorMsgsEl).removeClass( 'displayNone' ); $( response.errorMsgsEl + 'List' ).innerHTML = ''; if (response.errorMsgs) { for( var i = 0; i < response.errorMsgs.length; i++ ) { $( response.errorMsgsEl + 'List' ).innerHTML += response.errorMsgs[i]; } } if( response.errorIds ) { for( var j = 0; j < response.errorIds.length; j++ ) { if( $(response.errorIds[j]).getAttribute("type") == 'error' ) { $(response.errorIds[j]).addClass( 'highlightError' ); } } } window.scroll(0,0); } function enableBtn( buttonEnabled, buttonDisabled ) { if( buttonEnabled ) { buttonEnabled.removeClass( 'displayNone' ); } if( buttonDisabled ) { buttonDisabled.addClass( 'displayNone' ); } } function getPartnerCookie() { return getCookie('partner2'); } function handlePartnerOnReg(){ $('bizTypeRadio').checked = true; handleTypeChange('biz') ; $('bizSmall').checked = true; $('category6').checked = true; $('usermanagement').checked = false; handleMembershipChange(); var promocode = getCookie('promocode'); if(promocode) { $('promoCode').value = promocode; submitPromo(); } } function landingRedirect() { var url = document.URL; var elance = /elance\.com\/$/; var olsbPartner = getPartnerCookie(); var isOlsbPartner = (olsbPartner == 15622 || olsbPartner == 15623); if(url.match('/p/landing/') && url.indexOf('provider')>0 && !url.match('olsb') && isOlsbPartner) { window.location.href = '/officeliveprovider'; return; } if(isOlsbPartner && (url.match(elance) || url.match('/p/landing/') && url.indexOf('buyer')>0 && !url.match('olsb'))) { if(olsbPartner == 15622) { window.location.href = '/officelivebuyerpromo'; return; } else if(olsbPartner == 15623){ window.location.href = '/officelivebuyer'; } return; } if(url.match('olsb')) return; } function noThanksPartner( divid ) { var options = { url: '/php/partner/main/PartnerInterstitialAHR.php?action=nothanks&type='+divid, method: 'post', onSuccess: function(res) { $( divid ).addClass('displayNone') }, onFailure: handleError } var request = new Request(options); request.send(); } function clearGroup ( groupid ) { var options = { url: '/php/groups/main/groupAHR.php?action=ClearGroup&groupId='+groupid+'&t=' + getDateTime(), method: 'post', onSuccess: function(res) { if($('recommended_count')) { if($( 'recommended_count' ).value == 0 ) { $('recommended_list').addClass('displayNone'); } else { $( 'recommended_count' ).value = $( 'recommended_count' ).value - 1; } } if($( 'group' + groupid )) $( 'group' + groupid ).addClass('displayNone'); }, onFailure: handleError } curAsyncReq = new Request(options); curAsyncReq.send(); } EOL.namespace('editProfile'); EOL.editProfile.hideAutoShutOff = function() { new Request({ url: '/php/preferences/main/myavailabilityAHR.php?t=' + getDateTime(), method: 'post', data: 'action=hideAutoShutOff', onSuccess: function() { $('notavailablediv').addClass('displayNone'); if ($('setoff')) $('setoff').removeClass('displayNone'); }, onFailure: function() { alert('There was an error processing your request. Please refresh and try again.'); } }).send(); } EOL.namespace('profileImage'); // vars EOL.profileImage.uploading = false; EOL.profileImage.cropObj = null; /* Upload listener */ EOL.profileImage.addUploadListner = function() { if ($("uploadImageTarget")) { //alert('Adding event'); $("uploadImageTarget").addEvent('load', function() { if (!EOL.profileImage.uploading) return; try { var response = JSON.decode($("uploadImageTarget").contentWindow.document.body.innerHTML); } catch(e) { alert('There was an error processing your request. Please refresh and try again.'); } if (response) { //alert('in here 1'); EOL.profileImage.cropObj = null; if( response.status == 'success' && response.data) { $('imageMode').value = 'new'; var displayImage = response.data.profileImgDraftThumbData.url; /* Preview and save related setters */ $("tilePreview").src = displayImage; $("thumbPreview1").src = displayImage; $("thumbPreview2").src = displayImage; // set proper thumb preview block if($("existingThumbPreview")) { $("existingThumbPreview").style.display = 'none'; } $("cropThumbPreview").style.display = 'none'; $("fullThumbPreview").style.display = ''; $('groupId').value = response.data.groupId; $('saveSection').style.display = ''; $('loadingIcon').style.display = 'none'; $('previewArea').style.display = ''; /* Crop related setters */ $('cropframe').style.backgroundImage = "url('" + displayImage + "')"; var imglayer = $('imglayer'); imglayer.setStyle('background-image', "url('" + displayImage + "')"); imglayer.setStyle('width', response.data.profileImgDraftThumbData.width); imglayer.setStyle('height', response.data.profileImgDraftThumbData.height); $('scaleToFitImage').src = displayImage; // Hide any Error messages $('imageSaveError').style.display = 'none'; $('imageDeleteError').style.display = 'none'; $('imageDraftError').style.display = 'none'; //enable 'set ad my profile picture' button $('setButton').addClass('btn-large-normal'); $('setButton').removeClass('btn-large-disabled'); //Initializing the crop object is done when the crop area is displayed. because of the offsetParent requires the elements to be visible. } else if( response.status == 'error' ) { EOL.profileImage.handleUploadErrors(response); } enableElems($('save-action-buttons')); } else { alert('There was an error processing your request. Please refresh and try again.'); } EOL.profileImage.uploading = false; }); } } EOL.profileImage.handleUploadErrors = function(res) { var errorArr = res.errorMsgs; $('imageDraftErrMsg').innerHTML = ''; for( var i = 0; i < errorArr.length; i++ ) { //alert(errorArr[i] + '-' + errorArr[i].indexOf('435')); if(errorArr[i].indexOf('435') >= 0) $('imageDraftErrMsg').innerHTML += '
  • Selected file type is not supported. Please use jpeg, gif or png file.
  • '; else $('imageDraftErrMsg').innerHTML += '
  • ' + errorArr[i] + '
  • '; } $('imageDraftError').style.display = ''; $('saveSection').style.display = 'none'; } /* END- Upload listener */ /* Dialog */ EOL.profileImage.dialog = null; EOL.profileImage.open = function(context) { //alert('test'); EOL.profileImage.cropObj = null; var request = new Request({ url: '/php/profile/main/profileImageUploadHTML.php?context=' + context + '&t=' + getDateTime(), method: 'get', onSuccess: function(req) { addCSS('/styles/profile/profileImageUpload.css'); EOL.profileImage.dialog = new EOL.dialog(req, {id:'imageUploadDialog', position: 'fixed', modal:true, close:true}); EOL.profileImage.dialog.show(); EOL.profileImage.addUploadListner(); }, onFailure: function() {} }).send(); } EOL.profileImage.close = function() { EOL.profileImage.dialog.hide(); } /* END- Dialog */ /* Interaction actions */ EOL.profileImage.toggleUploadAndCropSection = function() { if($('cropSection').style.display != '') { $('cropSection').style.display = ''; $('uploadAndSaveSection').style.display = 'none'; // cwCrop Object needs to be initialzed when the crop divs are not display:none i.e. they are visible. Firefox and chrome does not return offsetParent if the elements are display:none if(!EOL.profileImage.cropObj) { EOL.profileImage.initializeCropObj(); } } else { $('cropSection').style.display = 'none'; $('uploadAndSaveSection').style.display = ''; } } EOL.profileImage.initializeCropObj = function() { //alert('initializing crop'); EOL.profileImage.cropObj = new CwCrop({ onCrop: function(values) { //alert('On crop called'); $('cropX').value = values.x; $('cropY').value = values.y; $('cropWidth').value = values.w; $('cropHeight').value = values.h; //alert("Selected area is: " + values.x + "," + values.y + " @ " + values.w + " x " + values.h); }, minsize: {x: 64, y: 80}, initialposition: {x: 30, y: 30}, imgframe: "imglayer", fixedratio: 0.8 }); } EOL.profileImage.handleScaleToFitToggle = function() { var scaleToFit = $$('input[type=checkbox][name=scaleToFit]')[0]; if(scaleToFit.checked == true) { $('cropArea').setStyle('display', 'none'); $('scaleToFitArea').setStyle('display', ''); } else { $('scaleToFitArea').setStyle('display', 'none'); $('cropArea').setStyle('display', ''); } } EOL.profileImage.handlePrepareThumbAction = function() { var scaleToFit = $$('input[type=checkbox][name=scaleToFit]')[0]; if($('existingThumbPreview')) { $('existingThumbPreview').setStyle('display', 'none'); } if(scaleToFit.checked == true) { $('thumbMode').value = 'full'; $('cropThumbPreview').setStyle('display', 'none'); $('fullThumbPreview').setStyle('display', ''); } else { EOL.profileImage.handleCropAction(); $('thumbMode').value = 'crop'; //set the display of cropped thumb var magnifyRatio = $('cropWidth').value/64; //alert('magnifyRatio' + magnifyRatio ); //alert($('imglayer').getStyle('width') + '-' +$('imglayer').getStyle('height')); var cropThumbW = (parseFloat($('imglayer').getStyle('width')))/magnifyRatio; var cropThumbH = (parseFloat($('imglayer').getStyle('height')))/magnifyRatio; var marginLeft = -Math.round(parseFloat($('cropX').value)/magnifyRatio); var marginTop = -Math.round(parseFloat($('cropY').value)/magnifyRatio); var thumbPreview2 = $('thumbPreview2'); //alert('cropThumbW-' + cropThumbW + '-' + 'cropThumbH-' + cropThumbH + '-marginLeft' + marginLeft + '-marginTop' + marginTop); thumbPreview2.setStyle('width', cropThumbW); thumbPreview2.setStyle('height', cropThumbH); thumbPreview2.setStyle('margin-left', marginLeft); thumbPreview2.setStyle('margin-top', marginTop); $('fullThumbPreview').setStyle('display', 'none'); $('cropThumbPreview').setStyle('display', ''); } EOL.profileImage.toggleUploadAndCropSection(); } EOL.profileImage.handleCropAction = function() { EOL.profileImage.cropObj.doCrop(); } /* END - Interaction actions */ /* AHRs */ EOL.profileImage.handleCreateDraft = function() { EOL.profileImage.uploading = true; disableElems($('save-action-buttons')); $('setButton').addClass('btn-large-disabled'); $('setButton').removeClass('btn-large-normal'); /* flip loading image and preview area */ $('loadingIcon').style.display = ''; $('previewArea').style.display = 'none'; /* END FLIP */ $('imageDraftError').style.display = 'none'; $('imageDraftForm').submit(); } // Save Image EOL.profileImage.handleSaveImage = function() { $('imageDraftError').style.display = 'none'; var postData = $('imageSaveForm').toQueryString(); disableElems($('save-action-buttons')); $('setButton').addClass('btn-large-disabled'); $('setButton').removeClass('btn-large-normal'); var options = { url: '/php/profile/main/profileImageUploadAHR.php?t=' + getDateTime(), method: 'post', data: postData, onSuccess: EOL.profileImage.handleSaveImageSuccess, onFailure: function() { alert('There was an error processing your request. Please refresh and try again.'); } }; curAsyncReq = new Request(options); curAsyncReq.send(); } EOL.profileImage.handleSaveImageSuccess = function( obj ) { //-- read JSON data var response = eval('(' + obj + ')'); if( response.status == 'success' ) { if($('profileImage') && response.data.profileUrl) { $('profileImage').src = response.data.profileUrl; enableElems($('save-action-buttons')); $('setButton').addClass('btn-large-normal'); $('setButton').removeClass('btn-large-disabled'); EOL.profileImage.dialog.hide(); } else { var current = document.location.href; if(current.indexOf("?pledge=taken") > 0){ var redirectTo = current.replace('?pledge=taken',''); window.location = redirectTo; }else window.location = window.location.href.split('#')[0]; } } else if( response.status == 'error' ) { disableElems($('save-action-buttons')); $('setButton').addClass('btn-large-disabled'); $('setButton').removeClass('btn-large-normal'); var errorArr = response.errorMsgs; $('imageSaveErrMsg').innerHTML = ''; for( var i = 0; i < errorArr.length; i++ ) { $('imageSaveErrMsg').innerHTML += '
  • ' + errorArr[i] + '
  • '; } $('imageSaveError').style.display = ''; } } // Delete Image EOL.profileImage.handleDeleteImageAction = function() { var options = { url: '/php/profile/main/profileImageUploadAHR.php?mode=DeleteImage&context=' + $('context').value + '&t=' + getDateTime(), method: 'post', onSuccess: EOL.profileImage.handleDeleteImageSuccess, onFailure: function() { alert('There was an error processing your request. Please refresh and try again.'); } }; curAsyncReq = new Request(options); curAsyncReq.send(); } EOL.profileImage.handleDeleteImageSuccess = function( obj ) { var response = eval('(' + obj + ')'); if( response.status == 'success' ) { //refresh the entire page to update state of other components window.location.href = window.location.href.replace('#',''); return; } else if(response.status == 'error') { var errorArr = response.errorMsgs; $('imageDeleteErrMsg').innerHTML = ''; for( var i = 0; i < errorArr.length; i++ ) { $('imageDeleteErrMsg').innerHTML += '
  • ' + errorArr[i] + '
  • '; } $('imageDeleteError').style.display = ''; } } /* END- AHRs */ /** * @namespace EOL * @namespace EOL.utility * @namespace EOL.smartererTestWidget */ EOL.namespace('smartererTestWidget'); EOL.namespace('smartererTestWidget.developer'); EOL.smartererTestWidget.requestHandler = '/php/widget/main/smartererTestWidgetAHR.php'; EOL.smartererTestWidget.enableEventTracking = EOL.smartererTestWidget.enableEventTracking?EOL.smartererTestWidget.enableEventTracking:true; EOL.smartererTestWidget.eventTrackingDefaults = { category:'Smarterer', actions:{'click':'click'},//domEvent to action map label:window.parent?window.parent.location.pathname:window.location.pathname }; EOL.smartererTestWidget.trackEvent = function(options){ return EOL.utility.trackEvent(options); }; EOL.smartererTestWidget.initTrackableElements = function(context){ return EOL.utility.initTrackableElements('data-smartererTestWidgetTrackable', EOL.smartererTestWidget.eventTrackingDefaults, context); }; EOL.smartererTestWidget.smartererBaseUrl = 'https://smarterer.com'; EOL.smartererTestWidget.initSafariWorkAround = function(){ if (Browser.safari && !Cookie.read('smartererWidgetSafariWorkAround')) { var safariHackWindow = window.open(EOL.smartererTestWidget.smartererBaseUrl, '_blank'); window.focus(); setTimeout(function(){ safariHackWindow.close(); }, 3000); Cookie.write('smartererWidgetSafariWorkAround', true); } }; EOL.smartererTestWidget.init = function() { EOL.smartererTestWidget.initTrackableElements(); }; /** * @TODO * - Refactor to extend EOL.Modal (the now generalize remote modal logic (duplicated in smarterer, teamAdoption, featuredUpsell)) * - clean up design to take better advantage of MooTools Events and Options class extras */ EOL.smartererTestWidget.modal = new Class({ Implements:[Events,Options], modalRequest:null, //used by extending classes to add GET params to the modal ajax request modalRequestParameters:{}, dialog:null, modalUrl:null, modalUrlAction:null, height:null, width:null, eventTrackingDefaults:{}, communicationErrorMessage:'Unable to communicate with Elance, please refresh and try again.', onCommunicationError: function(response) { if (console && console.log) { console.log(response); } alert(this.communicationErrorMessage); }, className:'', trackDataAttributeName:'', smartererTestSlug:'', //onClose must call completeClose, which allows for asynchronous behaviour onClose: function(completeClose){completeClose();}, //redirect:null, optionDefaults:{ modalUrl: EOL.smartererTestWidget.requestHandler, modalUrlAction:null, height:null, width:null, className:'', smartererTestSlug:'', //redirect:window.location.href, trackDataAttributeName:'data-smartererTestWidgetModalTrackable', eventTrackingDefaults:Object.merge({}, this.eventTrackingDefaults, EOL.smartererTestWidget.eventTrackingDefaults, {label:null}),//label calculated by modal on initialization by default enableEventTracking:EOL.smartererTestWidget.enableEventTracking, showCloseButton:true, onTestResultsUpdated:function(){} }, options:{},//used by extending classes to override default options initialize: function(options){ this.options = Object.merge({}, this.optionDefaults, this.options, options); this.options.eventTrackingDefaults.label = this.getEventTrackingLabel(); var self = this; if (!this.options.smartererTestSlug){ //hack, don't have time to generalize modal //throw "You must supply the smarterer test slug for the test the user wants to take"; } if (!this.options.modalUrl){ throw "You must supply the url where the modal can be fetched"; } if (!this.options.modalUrlAction){ throw "You must supply the controller action (i.e. SyllabusModal)"; } this.setObjectAttributesFromOptions(); this.width = EOL.utility.varToCssDimension(this.width); this.height = EOL.utility.varToCssDimension(this.height); this.dialog = new EOL.dialog('', { position: 'scroll', className:'smartererDialog '+this.className, width:this.width,height:this.height}); //used for any additional parameters to be sent in modal request by extending classes var requestOptions = { 'url':this.modalUrl, 'data':Object.merge({},{'action':this.modalUrlAction, 'smartererTestSlug':this.smartererTestSlug},this.modalRequestParameters), 'method':'get', 'onSuccess':function(response){ if (response.status && response.status == 'error') { self.dialog.hide(); if (!EOL.smartererTestWidget.errorDialog) { EOL.smartererTestWidget.errorDialog = new EOL.dialog(response.data.html, {position: 'fixed', modal:true, width:580, close:true}); } EOL.smartererTestWidget.errorDialog.show(); } else { self.update(response.data.modalContent); } }, 'onFailure':function(response){ self.onCommunicationError(response); } }; this.modalRequest = new Request.JSON(requestOptions); window.addEvent('resize',function(){ if ($(self.dialog.containerEl)){ self.dialog.resize(); } }); this.setOptions(options); }, setObjectAttributesFromOptions: function(){ var self = this; Object.each(this.options, function(item, key){ self[key] = item; }); }, trackEvent: function(options){ if (typeof options != "object"){ options = {action:options};//if options is a string then it's the name of the action to track } options = Object.merge({}, this.eventTrackingDefaults, options); EOL.smartererTestWidget.trackEvent(options); }, getEventTrackingLabel: function(){ if (this.options.eventTrackingDefaults.label == null){ this.options.eventTrackingDefaults.label = EOL.smartererTestWidget.eventTrackingDefaults.label + '#' + this.options.modalUrlAction; } return this.options.eventTrackingDefaults.label; }, //This should be used to open the model as a response to the user interacting directly with a UI element. open: function(){ this.trackEvent('open'); this.show(); }, //This should be used to open the model as a secondary result of a user interaction (i.e. another interaction caused a state in which this modal should be displayed) show: function(){ this.showLoading(); this.modalRequest.send(); }, //this is used to close the modal as a secondary result of a tracked user interaction, but it should not be tracked hide: function(){ this.dialog.hide(); }, //this maps to ui elements that the user interacts with, which have the intent of closing the modal, these should be tracked close: function(){ var self = this; var completeClose = function(){ self.trackEvent('close'); self.hide(); }; this.onClose(completeClose); }, resetCloseButton: function(){ var self = this; if ($(this.dialog.containerEl)){ var oldCloseButton = $(this.dialog.containerEl).getElement('.eol-dialog-close'); if (this.showCloseButton){ //this removes event handlers var newCloseButton = oldCloseButton.clone(); //setup new handler newCloseButton.addEvent('click', function(){ self.close(); }); //append new close button newCloseButton.inject(oldCloseButton, 'after'); } oldCloseButton.dispose(); } }, showLoading: function(){ this.dialog.show(); var dialogContainer = $(this.dialog.containerEl); var loadIndicator = dialogContainer.getElement('.smarterer-widget-loading-indicator'); if (!loadIndicator){ loadIndicator = new Element('div', { 'class':'smarterer-widget-loading-indicator' }); loadIndicator.inject(dialogContainer, 'top'); } dialogContainer.addClass('loading'); //lazy reset of close button this.resetCloseButton(); }, hideLoading: function(){ var dialogContainer = $(this.dialog.containerEl); dialogContainer.removeClass('loading'); }, update: function(htmlContent){ this.hideLoading(); this.dialog.update(htmlContent); var self = this; var addButtons = $(this.dialog.containerEl).getElements('a.action'); if(addButtons){ addButtons.each(function(item){ if (item.get(self.trackDataAttributeName)){ var trackData = Object.merge( {}, self.eventTrackingDefaults, item.get(self.trackDataAttributeName)?JSON.decode(item.get(self.trackDataAttributeName)):{} ); Object.each(trackData.actions, function(action, domEvent){ item.addEvent(domEvent, function(){ var localTrackData = Object.merge({}, trackData); localTrackData.action = action; delete localTrackData.actions; self.trackEvent(localTrackData); }); }); } }); addButtons.addEvent('mouseenter', function(){ this.addClass('hover'); }); addButtons.addEvent('mouseleave', function(){ this.removeClass('hover'); }); } }, turnInvisible:function(){ $(this.dialog.containerEl).setStyle('visibility','hidden'); }, turnVisible:function(){ $(this.dialog.containerEl).setStyle('visibility','visible'); } }); /** * @constructor */ EOL.smartererTestWidget.masterIFrameModal = (function(){ return new Class({ Extends:EOL.smartererTestWidget.modal, options: { className:'masterIFrameModel', modalUrlAction: 'MasterIFrameModel' }, open:function(){ var self = this; //javascript is the future because of these types of abilities this.boundWindowEventCloseRequestHandler = function(){ self.close(); }.bind(this); this.boundWindowEventTestResultsCloseRequestHandler = function(){ self.fireEvent('testResultsUpdated'); self.close(); }.bind(this); window.addEvent('smartererTestWidgetCloseRequest', this.boundWindowEventCloseRequestHandler); window.addEvent('smartererTestWidgetTestResultsCloseRequest', this.boundWindowEventTestResultsCloseRequestHandler); this.parent(); }, close:function(){ window.removeEvent('smartererTestWidgetCloseRequest', this.boundWindowEventCloseRequestHandler); window.removeEvent('smartererTestWidgetTestResultsCloseRequest', this.boundWindowEventTestResultsCloseRequestHandler); this.parent(); } }); })(); /** * @constructor */ EOL.smartererTestWidget.notReachedMinThresholdModal = new Class({ Extends:EOL.smartererTestWidget.modal, options: { modalUrlAction: 'NotReachedMinThresholdModal', className:'notReachedMinThresholdModal', showCloseButton:false }, onResumeTest:function(){ return true; }, onExitTest:function(){ return true; }, update:function(htmlContent){ this.parent(htmlContent); var self = this; //the actions buttons on this modal don't natively have a behavior, delegate behavior to event handlers $(this.dialog.containerEl).getElements('.action.resumeTest').addEvent('click', function(){ self.onResumeTest(); }); $(this.dialog.containerEl).getElements('.action.exitTest').addEvent('click', function(){ self.onExitTest(); }); } }); EOL.smartererTestWidget.showNotReachedMinThresholdModal = function(options){ var modal = new EOL.smartererTestWidget.notReachedMinThresholdModal(options); modal.open(); }; /** * @constructor */ EOL.smartererTestWidget.nonFreelancerModal = new Class({ Extends:EOL.smartererTestWidget.modal, options: { modalUrlAction: 'NonFreelancerModal', className:'nonFreelancerModal' } }); EOL.smartererTestWidget.showOutOfQuestionsModal = function(smartererTestSlug){ var options = { smartererTestSlug:smartererTestSlug }; var modal = new EOL.smartererTestWidget.outOfQuestionsModal(options); modal.open(); }; /** * @constructor */ EOL.smartererTestWidget.outOfQuestionsModal = new Class({ Extends:EOL.smartererTestWidget.modal, options: { modalUrlAction: 'OutOfQuestionsModal', className:'outOfQuestionsModal' }, onExit:function(e){ e.stop(); this.hide(); }, update:function(htmlContent){ this.parent(htmlContent); var self = this; //the actions buttons on this modal don't natively have a behavior, delegate behavior to event handlers $(this.dialog.containerEl).getElements('.action.exit').addEvent('click', function(e){ self.onExit(e); }); } }); EOL.smartererTestWidget.showNonFreelancerModal = function(options){ var modal = new EOL.smartererTestWidget.nonFreelancerModal(options); modal.open(); }; //gets toggled on/off on certain pages (syllabus page, test results page) EOL.smartererTestWidget.confirmReachedMinThresholdBeforeExit = false; EOL.smartererTestWidget.setupSyllabusTakeTestButton = function(){ $$('#smartererTestingWidgetSyllabusModalContent .action.takeTest').addEvent('click',function(){ $$('body').setStyle('background','transparent').set('html',''); EOL.smartererTestWidget.setConfirmReachedMinThresholdBeforeExit(true); EOL.smartererTestWidget.setModalClass('smartererTestFlow', true); }); }; EOL.smartererTestWidget.setupResumeTestBeginTestButton = function(){ $$('#smartererTestingWidgetResumeTestModalContent .action.beginTest').addEvent('click',function(){ $$('body').setStyle('background','transparent').set('html',''); EOL.smartererTestWidget.setConfirmReachedMinThresholdBeforeExit(true); EOL.smartererTestWidget.setModalClass('smartererTestFlow', true); }); $$('#smartererTestingWidgetResumeTestModalContent .syllabusModalLink').addEvent('click',function(){ $$('body').setStyle('background','transparent').set('html',''); EOL.smartererTestWidget.setConfirmReachedMinThresholdBeforeExit(false); EOL.smartererTestWidget.setModalClass('syllabus', true); }); }; EOL.smartererTestWidget.setConfirmReachedMinThresholdBeforeExit = function(shouldCheck){ EOL.smartererTestWidget.confirmReachedMinThresholdBeforeExit = shouldCheck; var parentWindow = EOL.smartererTestWidget.getParentWindow(); if (parentWindow){ parentWindow.EOL.smartererTestWidget.confirmReachedMinThresholdBeforeExit = shouldCheck; } }; EOL.smartererTestWidget.setModalClass=function(className, testParent){ var storedOriginalClasses = $$('html').getProperty('data-smartererTestWidget-originalClasses'); if(!storedOriginalClasses){ var originalClasses = $$('html').getProperty('class'); $$('html').setProperty('data-smartererTestWidget-originalClasses', originalClasses); storedOriginalClasses = originalClasses; } $$('html').setProperty('class',storedOriginalClasses); $$('html').addClass(className); //console.debug(storedOriginalClasses); //console.debug($$('html').getProperty('class')); window.fireEvent('resize'); if (testParent){ var parentWindow = EOL.smartererTestWidget.getParentWindow(); if (parentWindow){ parentWindow.EOL.smartererTestWidget.setModalClass(className, false); } } }; EOL.smartererTestWidget.getParentWindow = function(){ if(window.parent && (window.parent !== window) && window.parent.EOL && window.parent.EOL.smartererTestWidget){ return window.parent; } else { return window; } }; /** * Starts smarter testing widget test flow * * @deprecated Use EOL.smartererTestWidget.startTestFlow with correct options instead * * @see EOL.smartererTestWidget.startTestFlow * @param smartererTestSlug * @param elanceCallToAction * @param options */ EOL.smartererTestWidget.showModalByCallToAction = function(smartererTestSlug, elanceCallToAction, options){ options = Object.merge((options || {}), { /** * This is a bad place for redirection. This is here for backward compatibility, which is why this method is now deprecated. * Call to actions are now updated automatically. Edge case exists where test score tooltips are not generated until a reload. * If this is an issue, just uncomment the line below. */ onTestResultsUpdated:function(){ //EOL.smartererTestWidget.getParentWindow().location.reload(); }, smartererTestSlug:smartererTestSlug, elanceCallToAction:elanceCallToAction }); //click tracking moved here so that take/resume links can be swapped out dynamically switch(elanceCallToAction) { case 'take': //no tracking break; case 'improve': EOL.smartererTestWidget.testTrack('CLICK','ImproveScore','SkillPage', smartererTestSlug); break; default: case 'resume': EOL.smartererTestWidget.testTrack('CLICK','ResumeTest','SkillPage', smartererTestSlug); break; } EOL.smartererTestWidget.startTestFlow(options); }; EOL.smartererTestWidget.startTestFlow = function(options){ //if options is a string it is assumed to be the test slug var smartererTestSlug, elanceCallToAction = 'take'; if (typeOf(options) == 'string'){ smartererTestSlug = options; options = {}; } else if (typeOf(options) == 'object') { smartererTestSlug = options.smartererTestSlug; elanceCallToAction = options.elanceCallToAction?options.elanceCallToAction:elanceCallToAction; } else { throw Error('Invalid parameter "options". It can either be the smarterer test url slug or an object containing configuration options'); return; } if (elanceCallToAction == 'out_of_questions'){ EOL.smartererTestWidget.showOutOfQuestionsModal(smartererTestSlug); return; } else if (elanceCallToAction == 'take'){ //syllabus modal will be shown so preemptively change modal class EOL.smartererTestWidget.setModalClass('syllabus', false); } else { //resume test modal will be shown so preemptively change modal class EOL.smartererTestWidget.setModalClass('resumeTest', false); } EOL.smartererTestWidget.showMasterIFrameModal(smartererTestSlug, elanceCallToAction, options); } EOL.smartererTestWidget.showMasterIFrameModal = function (smartererTestSlug, elanceCallToAction, options) { options = options || {}; if (Browser.safari) { EOL.smartererTestWidget.initSafariWorkAround(); } options = Object.merge(options, { 'smartererTestSlug':smartererTestSlug, 'onClose':function(completeTestModalClose){ var testModal = this; var requestOptions = { /** * * @param response * @param response.data * @param response.data.continueWithoutConfirmation */ onSuccess: function(response){ if (response.data && response.data.continueWithoutConfirmation) { //Set 'take' link to 'improve' if threshold met if (response.data.badge != null && response.data.badge.min_threshold) { $$('.' + smartererTestSlug + '.take, .' + smartererTestSlug + '.resume').each(function(el) { $(el).removeClass('take').removeClass('resume').addClass('improve').set('text', 'Improve Score').set('href', $(el).get('href').replace('take', 'improve').replace('resume', 'improve')); }); //Set 'take' link to 'resume' if score > 0 } else if (response.data.badge != null && response.data.badge.score > 0) { $$('.' + smartererTestSlug + '.take').each(function(el) { $(el).removeClass('take').addClass('resume').set('text', 'Resume Test').set('href', $(el).get('href').replace('take', 'resume')); }); } completeTestModalClose(); } else if (EOL.smartererTestWidget.confirmReachedMinThresholdBeforeExit) { testModal.turnInvisible(); EOL.smartererTestWidget.showNotReachedMinThresholdModal({ smartererTestSlug:smartererTestSlug, onClose:function(completeMinThresholdModalClose){ completeMinThresholdModalClose(); testModal.turnVisible(); }, onResumeTest:function(){ this.hide(); testModal.turnVisible(); }, onExitTest: function(){ //Set 'take' link to 'improve' if threshold met if (response.data.badge != null && response.data.badge.min_threshold) { $$('.' + smartererTestSlug + '.take, .' + smartererTestSlug + '.resume').each(function(el) { $(el).removeClass('take').removeClass('resume').addClass('improve').set('text', 'Improve Score').set('href', $(el).get('href').replace('take', 'improve').replace('resume', 'improve')); }); //Set 'take' link to 'resume' if score > 0 } else if (response.data.badge != null && response.data.badge.score > 0) { $$('.' + smartererTestSlug + '.take').each(function(el) { $(el).removeClass('take').addClass('resume').set('text', 'Resume Test').set('href', $(el).get('href').replace('take', 'resume')); }); } this.hide(); completeTestModalClose();//completing the close of the testing modal EOL.smartererTestWidget.testTrack('CLICK','ExitTest','SkillPage',smartererTestSlug); } }); } } }; //if no confirmation, close modal immediately if (!EOL.smartererTestWidget.confirmReachedMinThresholdBeforeExit) { completeTestModalClose(); } EOL.smartererTestWidget.testStatusCheck(smartererTestSlug, requestOptions); } }); if (elanceCallToAction){ options.modalRequestParameters = {elanceCallToAction:elanceCallToAction}; } EOL.smartererTestWidget.setConfirmReachedMinThresholdBeforeExit(false); var modal = new EOL.smartererTestWidget.masterIFrameModal(options); modal.open(); //return modal; }; EOL.smartererTestWidget.testStatusCheck = function(smartererTestSlug, requestOptions){ var options = { url:EOL.smartererTestWidget.requestHandler, data:{ action:'FetchTestStatus', smartererTestSlug:smartererTestSlug, format:'json' } }; options = Object.merge({},options, requestOptions); var testStatusCheck = new Request.JSON(options); testStatusCheck.send(); }; EOL.smartererTestWidget.triggerSmartererTestWidgetCloseRequest = function (){ var parentWindow = EOL.smartererTestWidget.getParentWindow(); if (parentWindow){ parentWindow.fireEvent('smartererTestWidgetCloseRequest'); } }; EOL.smartererTestWidget.triggerSmartererTestWidgetTestResultsCloseRequest = function (){ var parentWindow = EOL.smartererTestWidget.getParentWindow(); if (parentWindow){ parentWindow.fireEvent('smartererTestWidgetTestResultsCloseRequest'); } }; EOL.smartererTestWidget.setupTestResultsResumeTestButton = function(){ $$('#smartererTestingWidgetTestResultsModalContent .action.improveScore').addEvent('click',function(){ $$('body').setStyle('background','transparent').set('html',''); EOL.smartererTestWidget.setConfirmReachedMinThresholdBeforeExit(true); EOL.smartererTestWidget.setModalClass('smartererTestFlow', true); }); }; /** * * @param actionType * @param objectName * @param source * @param testName */ EOL.smartererTestWidget.testTrack = function(actionType, objectName, source, testName){ var userId = getCookie('userid'); /** @global */ $el('send', 'useraction', actionType, objectName, { 'userId':userId, 'pageName': source, 'metricTags': { 'TestName': testName } }); };